/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 /***************************************************************************
 * Name: thread_pool.h
 *
 * Purpose: thread pool implementation
 *
 * Developer:
 *   wen.gu , 2019-07-04
 *
 * TODO:
 *
 ***************************************************************************/

/******************************************************************************
 **    INCLUDES
 ******************************************************************************/
#ifndef __CORE_THREAD_POOL_H__
#define __CORE_THREAD_POOL_H__

#include <vector>
#include <atomic>
#include <queue>
#include <future>
#include <memory>

#include "panda/core/types.h"
#include "panda/core/errors.h"

namespace panda
{
namespace core
{
/******************************************************************************
 **    MACROS
 ******************************************************************************/
#define  MAX_THREAD_NUM 16

/******************************************************************************
 **    TYPE DEFINITIONS
 ******************************************************************************/



/******************************************************************************
 **    CLASSES/FUNCTIONS DEFINITIONS
 ******************************************************************************/

class CORE_CLASS ThreadPool final
{
public:
    using Task = std::function<void()>;
public:
    ThreadPool(uint32_t maxThreadCnt = MAX_THREAD_NUM);
    ~ThreadPool();
public:
    /** threadCnt: see also MAX_THREAD_NUM */
    PandaErrc start(uint32_t threadCnt = 4);
    PandaErrc stop();

    uint32_t idlThreadCount() const;
    uint32_t threadCount() const;
public:
    /** add a task to thread pool.
     * call .get() from addTask result to wait task come to end and get result.
     * add member function of class to thread pool:
     * bind：   .addTask(std::bind(&Dog::sayHello, &dog));
     * mem_fn： .addTask(std::mem_fn(&Dog::sayHello), this);
     */

    template<class F, class... Args>
    auto addTask(F&& f, Args&&... args) ->std::future<decltype(f(args...))>
    {
        // typename std::result_of<F(Args...)>::type, the result of function f.
        using RetType = decltype(f(args...));  
        auto task = std::make_shared<std::packaged_task<RetType()> >(
                std::bind(std::forward<F>(f), std::forward<Args>(args)...)
            );    // wtf !

        std::future<RetType> future = task->get_future();

        PandaErrc ret = commitTask([task]() {(*task)(); });

        if (ret != PandaErrc::OK)
        {
            throw std::runtime_error("add task on to threadPool failed.");
        } 

        return future;
    }

public:
    PandaErrc commitTask(Task task);

private:
    class impl;
    std::unique_ptr<impl> mImpl;
};

} /** namespace core */
} /** namespace panda */

#endif /** !__CORE_THREAD_POOL_H__ */